package nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author 张开顺
 * @title: SelectorClient
 * @projectName netty
 * @description: TODO
 * @date 2019/4/129:35
 */
public class SelectorClient {

    public static void main(String[] args) {
        ExecutorService executorService= Executors.newCachedThreadPool();
        executorService.submit(new Client("client-1"));
        executorService.submit(new Client("client-2"));
        executorService.submit(new Client("client-3"));
        executorService.submit(new Client("client-4"));
        executorService.shutdown();

    }


    static class Client extends Thread {
        private String name;
        private Random random = new Random(47);

        Client(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try{
                SocketChannel socketChannel=SocketChannel.open();
                socketChannel.configureBlocking(false);
                socketChannel.connect(new InetSocketAddress("127.0.0.1",1234));
                while(!socketChannel.finishConnect()){
                    TimeUnit.MILLISECONDS.sleep(100);
                }
                ByteBuffer buffer=ByteBuffer.allocate(1024);
                for(int i=0;i<5;i++){
                    TimeUnit.MILLISECONDS.sleep(100*random.nextInt(10));
                    String str = "Message from " + name + ", number:" + i;
                    buffer.put(str.getBytes());
                    buffer.flip();
                    while(buffer.hasRemaining()){
                        socketChannel.write(buffer);
                    }
                    buffer.clear();

                }
                socketChannel.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
